package com.snail.util;

import org.apache.log4j.Logger;

import java.io.*;
import java.util.Properties;

public class ProUtils {

    public static final Logger log = Logger.getLogger(ProUtils.class);

    public static String custPropertiesPath = "conf.properties";

    public static Properties custProperties = new Properties();
    static {
        try {
            custProperties.load(getConfInputStream());
        } catch (Exception e) {
            log.error("load custPropertiesPERTIES fial !");
        }
    }

    private static InputStream getConfInputStream() throws UnsupportedEncodingException {
        return getConfInputStream(custPropertiesPath);
    }

    private static InputStream getConfInputStream(String path) throws UnsupportedEncodingException {
        return ProUtils.class.getClassLoader().getResourceAsStream(path);
    }

    /**
     * 返回属性文件Properties.
     * @return
     * @throws IOException
     */
    public static Properties getPro() throws IOException {
        if (custProperties == null) {
            custProperties = createProperties(custPropertiesPath);
        }
        if (custProperties.isEmpty()) {
            custProperties.load(getConfInputStream());
        }
        return custProperties;
    }

    /**
     * 重新加载属性文件.
     * @throws IOException
     */
    public static void updatePro() throws IOException {
        if (custProperties == null) {
            custProperties = new Properties();
        }
        custProperties.load(getConfInputStream());
    }

    /**
     * 查询属性文件的内容.
     * @param key
     * @return
     */
    public static String getPropertyValue(String key) {
        return custProperties.getProperty(key);
    }

    /**
     * 构建Properties
     * @param propertiesFileName
     * @param inClassPath 文件名是否是CLASSPATH下的文件.
     * @return
     * @throws Exception
     */
    public static Properties createProperties(String propertiesFileName, boolean inClassPath) throws IOException {
        Properties properties = new Properties();
        if (inClassPath) {
            properties.load(getConfInputStream(propertiesFileName));
        } else {
            properties.load(new InputStreamReader(new FileInputStream(propertiesFileName), "UTF-8"));
        }
        return properties;
    }

    /**
     * 使用CLASSPATH下的文件创建Properties
     * @param propertiesFileName
     * @return
     * @throws Exception
     */
    public static Properties createProperties(String propertiesFileName) throws IOException {
        return createProperties(propertiesFileName, true);
    }

}
